<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.search"
        placeholder="模糊搜索"
        style="width: 200px;"
        size="small"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      ><i slot="prefix" class="el-input__icon el-icon-search" /></el-input>
      <el-select v-model="typeSelect" class="filter-item" clearable size="small" placeholder="请选择备件类型" @change="handleTypeFilter">
        <el-option
          v-for="item in typeDict"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="statusSelect" class="filter-item" clearable size="small" placeholder="请选择备件状态" @change="handleStatusFilter">
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <div class="filter-item">
        <el-date-picker
          v-model="inDateSelect"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="入库开始日期"
          end-placeholder="入库结束日期"
          value-format="yyyy-MM-dd"
          size="small"
          @change="handleDateSelect"
        />
      </div>
      <el-button
        v-if="checkPermission(['admin','sp_create','sp_all'])"
        class="filter-item"
        size="small"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >新增</el-button>
      <el-button
        class="filter-item"
        size="small"
        style="margin-left: 10px;"
        type="info"
        icon="el-icon-refresh"
        @click="handleRefresh"
      >清空</el-button>
    </div>
    <!--表格渲染-->
    <el-table v-if="checkPermission(['admin','sp_list','sp_all'])" v-loading="listLoading" :row-class-name="tableRowClassName" :data="list" border size="small" row-key="id">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="table-expand">
            <el-form-item label="PN">
              <span>{{ props.row.pn }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.create_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="更新时间">
              <span>{{ props.row.update_date | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
            </el-form-item>
            <el-form-item label="备注">
              <span>{{ props.row.remarks }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="备件状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">
            {{ scope.row.status ? '可用':'不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sn" label="SN" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sn }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="备件类型" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="size" label="规格" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.size }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="brand" label="品牌" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.brand }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="model" label="型号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.model }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="in_date" label="入库日期" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.in_date }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="warehouse" label="仓库" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.warehouse }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px" align="center">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(['admin','sp_edit','sp_all'])" type="primary" size="mini" @click="handleUpdate(scope.row)">
            编辑
          </el-button>
          <el-button v-if="checkPermission(['admin','sp_delete','sp_all'])" slot="reference" type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column></el-table>
    <!--分页组件-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="form" :inline="true" :rules="rules" size="small" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="备件类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="item in typeDict"
                  :key="item.value"
                  :label="item.value"
                  :value="item.value"
                />
              </el-select></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件品牌" prop="brand">
              <el-input v-model="form.brand" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备件型号" prop="model">
              <el-input v-model="form.model" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件SN" prop="sn">
              <el-input v-model="form.sn" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备件PN" prop="pn">
              <el-input v-model="form.pn" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件规格" prop="size">
              <el-input v-model="form.size" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="备件仓库" prop="warehouse">
              <el-input v-model="form.warehouse" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库日期" prop="in_date">
              <el-date-picker
                v-model="form.in_date"
                type="date"
                placeholder="选择日期"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" autosize />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
<script>
import { getDictByKey } from '@/api/dict'
import Pagination from '@/components/Pagination'
import checkPermission from '@/utils/permission'
import { getSP, delSP, addSP, editSP } from '@/api/spareparts'
export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      dialogFormVisible: false,
      dialogStatus: '',
      statusOptions: [{
        value: true,
        label: '可用'
      }, {
        value: false,
        label: '不可用'
      }],
      typeSelect: '',
      inDateSelect: '',
      statusSelect: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      listLoading: true,
      form: {
        type: '',
        sn: ''
      },
      typeDict: [],
      rules: {
        type: [
          { required: true, message: '请选择备件类型', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入SN', trigger: 'blur' }
        ]
      },
      listQuery: {
        page: 1,
        limit: 10,
        search: undefined
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.getList()
      this.getTypeDict()
    })
  },
  methods: {
    checkPermission,
    getTypeDict() {
      const key = 'SPAREPARTS_TYPE'
      getDictByKey(key).then(response => {
        for (const i of response) {
          if (i.SPAREPARTS_TYPE != null) { this.typeDict = i.SPAREPARTS_TYPE }
        }
      })
    },
    getList() {
      getSP(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count
        this.listLoading = false
        // Just to simulate the time of the request
        // setTimeout(() => {
        //   this.listLoading = false
        // }, 170)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDateSelect() {
      this.listQuery.in_date_after = this.inDateSelect[0]
      this.listQuery.in_date_before - this.inDateSelect[1]
      this.handleFilter()
    },
    handleRefresh() {
      this.typeSelect = ''
      this.statusSelect = ''
      this.inDateSelect = ' '
      this.listQuery.type = ''
      this.listQuery.in_date_before = ''
      this.listQuery.in_date_after = ''
      this.listQuery.status = ''
      this.handleFilter()
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除此行, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delSP(row.id).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
          this.handleFilter()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetForm() {
      this.form = {
        type: '',
        brand: '',
        model: '',
        sn: '',
        pn: '',
        size: '',
        warehouse: '',
        in_date: '',
        remarks: ''
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        // 清除
        this.$refs['dataForm'].resetFields()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addSP(this.form).then(() => {
            this.resetForm()
            // this.list.unshift(this.temp)
            this.$message({
              type: 'success',
              message: '创建成功!'
            })
            this.dialogFormVisible = false
            this.handleFilter()
          })
        }
      })
    },
    tableRowClassName({ row }) {
      if (row.status === false) {
        return 'warning-row'
      } else if (row.status === true) {
        return 'success-row'
      }
      return ''
    },
    handleUpdate(row) {
      this.resetForm()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        this.$refs['dataForm'].clearValidate()
        this.form = { ...row }
      })
    },
    handleTypeFilter() {
      this.listQuery.type = this.typeSelect
      this.handleFilter()
    },
    handleStatusFilter() {
      this.listQuery.status = this.statusSelect
      this.handleFilter()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editSP(this.form.id, this.form).then(() => {
            for (const v of this.list) {
              if (v.id === this.form.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.form)
                break
              }
            }
            this.dialogFormVisible = false
            this.$message({
              type: 'success',
              message: '更新成功!'
            })
            this.handleFilter()
          })
        }
      })
    }
  }
}
</script>
<style>
  .table-expand {
    font-size: 0;
  }
  .table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 25%;
  }
</style>
